package com.ywj.interview.thread;

public class ThreadLocalDemo {
    private String content;

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

//    public static void main(String[] args) {
//        ThreadLocalDemo demo = new ThreadLocalDemo();
//
//        for (int i = 0; i < 5; i++) {
//            Thread t = new Thread() {
//                @Override
//                public void run() {
//                    demo.setContent(Thread.currentThread().getName() + "的数据");
//                    System.out.println("~~~~~~~~~~~~~~");
//                    System.out.println(Thread.currentThread().getName() + "-->" + demo.getContent());
//                }
//            };
//            t.setName("线程" + i);
//            t.start();
//        }
//    }

    //使用同步锁synchronized
    public static void main(String[] args) {
        ThreadLocalDemo demo = new ThreadLocalDemo();

        for (int i = 0; i < 5; i++) {
            Thread t = new Thread() {
                @Override
                public void run() {
                    //加了锁的代码线程只能排队进行访问，失去了并发性
                    synchronized (ThreadLocalDemo.class) {
                        demo.setContent(Thread.currentThread().getName() + "的数据");
                        System.out.println("~~~~~~~~~~~~~~");
                        System.out.println(Thread.currentThread().getName() + "-->" + demo.getContent());
                    }
                }
            };
            t.setName("线程" + i);
            t.start();
        }
    }
}
